package com.zhongyouyun.lbyc.service.imp;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zhongyouyun.admin.model.UserModel;
import com.zhongyouyun.lbyc.excel.CustomBaseExcel;
import com.zhongyouyun.lbyc.model.CustomBaseModel;
import com.zhongyouyun.lbyc.mapper.CustomBaseMapper;
import com.zhongyouyun.lbyc.pojo.CustomBasePojo;
import com.zhongyouyun.lbyc.service.CustomBaseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhongyouyun.other.exception.BizException;
import com.zhongyouyun.utils.ExcelUtils;
import com.zhongyouyun.utils.ModelUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author: shenyi
 * @Date: 2023-11-14
 * @Description: 客户基础表服务实现类
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CustomBaseServiceImpl extends ServiceImpl<CustomBaseMapper, CustomBaseModel> implements CustomBaseService {
    /*
     * @Author: shenyi
     * @Date: 2021-09-08
     * @Description: 分页查询
     * @param page 分页数据  lambdaQueryWrapper where 条件 和排序
     */
    @Override
    public IPage<CustomBaseModel> selectPage(Page<CustomBaseModel> page, QueryWrapper<CustomBaseModel> queryWrapper) {
        return this.baseMapper.selectPage(page, queryWrapper);
    }


    /*
     * @Author: shenyi
     * @Date: 2021-09-08
     * @Description: 查询全部
     * @param   lambdaQueryWrapper where 条件 和排序
     */
    @Override
    public List<CustomBaseModel> selectList(QueryWrapper<CustomBaseModel> queryWrapper) {
        return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    public IPage<CustomBasePojo> selectPojoPage(Page page, QueryWrapper<CustomBasePojo> queryWrapper) {
        return this.baseMapper.selectPojoPage(page, queryWrapper);
    }

    @Override
    @Transactional
    public Boolean exportImp(MultipartFile file) {
        Boolean flag = false;
        try {
            List<CustomBaseExcel> customBaseExcelList = (List<CustomBaseExcel>) ExcelUtils.ReadExcelByAll(file, 2, -1, 1, CustomBaseExcel.class);
            if (customBaseExcelList.size() > 0) {
                List<CustomBaseModel> customBaseModelList = BeanUtil.copyToList(customBaseExcelList, CustomBaseModel.class);
                customBaseModelList.removeIf(customBaseModel -> ObjectUtil.isEmpty(customBaseModel.getCustomCode()));
                UserModel model = (UserModel) SecurityUtils.getSubject().getPrincipal(); // 获取当前登录用户
                ModelUtils modelutils = new ModelUtils();
                customBaseModelList.forEach(customBaseModel -> {
                    modelutils.initModel(customBaseModel, model.getId().toString());
                });
                saveOrUpdateBatchByCustomCode(customBaseModelList);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException(1, "导入错误", false);
        }
        return flag;
    }

    public boolean saveOrUpdateBatchByCustomCode(List<CustomBaseModel> list) {
        Assert.notEmpty(list, "error: list must not be empty");
        Class<?> cls = currentModelClass();
        TableInfo tableInfo = TableInfoHelper.getTableInfo(cls);
        Assert.notNull(tableInfo, "error: can not execute. because can not find cache of TableInfo for entity!");
        int size = list.size();
        executeBatch(sqlSession -> {
            int i = 1;
            for (CustomBaseModel entity : list) {
                Object customCode = ReflectionKit.getMethodValue(cls, entity, "customCode");
                if (StringUtils.checkValNull(customCode)) {
                    sqlSession.insert(sqlStatement(SqlMethod.INSERT_ONE), entity);
                } else {
                    LambdaQueryWrapper<CustomBaseModel> oneQuery = new LambdaQueryWrapper<CustomBaseModel>();
                    oneQuery.eq(CustomBaseModel::getCustomCode, customCode);
                    Map<String, Object> param = new HashMap<>();
                    param.put(Constants.ENTITY, entity);
                    param.put(Constants.WRAPPER, oneQuery);
                    sqlSession.update(sqlStatement(SqlMethod.UPDATE), param);
                }
                // 不知道以后会不会有人说更新失败了还要执行插入 😂😂😂
                if ((i % 1000 == 0) || i == size) {
                    sqlSession.flushStatements();
                }
                i++;
            }
        });
        return true;
    }
}
